// import 'package:cached_video_player_plus/cached_video_player_plus.dart';

import 'package:flutter/material.dart';
import 'package:hockey/extensions/jzx_widget_extension.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/models/jzx_media_data.dart';
import 'package:hockey/widgets/common/jzx_network_image_view.dart';
import 'package:lifecycle/lifecycle.dart';
import 'package:simple_animations/animation_builder/loop_animation_builder.dart';
import 'package:simple_animations/simple_animations.dart';
import 'package:video_player/video_player.dart';

import 'controller.dart';

class JzxVideoView extends StatefulWidget {
  const JzxVideoView({super.key});

  @override
  State<JzxVideoView> createState() => _JzxVideoViewState();
}

class _JzxVideoViewState extends State<JzxVideoView>
    with LifecycleAware, LifecycleMixin {
  final controller = Get.find<JzxVideoController>();

  @override
  void onLifecycleEvent(LifecycleEvent event) {
    controller.event = event;
    if (event == LifecycleEvent.invisible) {
      controller.disposePlayer();
    } else if (event == LifecycleEvent.visible && context.mounted) {
      controller.palyOhter(controller.pageCur);
    }
  }

  @override
  Widget build(BuildContext context) {
    // Dio().post(appDomain.host + kApiVideoSearch, data: [
    //   {"mediaPath": "StickFlow/video/1.mp4", "mediaType": "video"}
    // ]).then(print);

    return Scaffold(
      extendBodyBehindAppBar: true,
      resizeToAvoidBottomInset: false,
      appBar: JzxAAppBar(
        actions: [
          InkWell(
              onTap: () {
                controller.showOptions();
              },
              child: Assets.images.icNavMore
                  .image(width: 24)
                  .paddingOnly(right: 20)),
        ],
      ),
      backgroundColor: Colors.black,
      body: SizedBox(
        height: Get.height - Get.bottomBarHeight,
        child: GetBuilder<JzxVideoController>(
            init: controller,
            id: 'items',
            autoRemove: false,
            assignId: true,
            builder: (context) {
              if (controller.items.isEmpty) {
                return Center(
                  child: Assets.images.icEmpty.image(width: 200.w),
                ).backgroud(Assets.images.normalBgv);
              }
              return PageView.builder(
                scrollDirection: Axis.vertical,
                // physics: const ClampingScrollPhysics(),
                controller: controller.pageController,
                itemCount: controller.items.length,
                itemBuilder: (context, index) {
                  final item = controller.items[index];

                  return GetBuilder<JzxVideoController>(
                      init: controller,
                      autoRemove: false,
                      assignId: true,
                      id: 'video',
                      builder: (_) {
                        final showPlayer =
                            controller.showPlayer(index, item.value.url);
                        return GestureDetector(
                          onTap: () {
                            controller.playOrPauseVideo();
                          },
                          child: Stack(
                            children: [
                              _JzxVideo(item.value, showPlayer),
                              _JzxPlayIcon(showPlayer),
                              _JzxOptions(item),
                              _JzxTitle(item: item.value),
                              _JzxProgress(showPlayer),
                            ],
                          ),
                        );
                      });
                },
                onPageChanged: (value) {
                  controller.palyOhter(value);
                  // print(value);
                },
              );
            }),
      ),
    );
  }
}

class _JzxPlayIcon extends GetView<JzxVideoController> {
  const _JzxPlayIcon(
    this.showPlayer, {
    super.key,
  });

  final bool showPlayer;

  @override
  Widget build(BuildContext context) {
    // final showPlayer = controller.showPlayer(index, item.url);
    return Positioned.fill(
      child: Center(
        child: Visibility(
          visible: controller.showPlayIcon() || !showPlayer,
          child: Assets.images.icPlayer.image(width: 69.w),
        ),
      ),
    );
  }
}

class _JzxVideo extends GetView<JzxVideoController> {
  const _JzxVideo(
    this.item,
    this.showPlayer, {
    super.key,
  });

  final JzxMediaData item;
  final bool showPlayer;

  @override
  Widget build(BuildContext context) {
    return Positioned.fill(
      child: showPlayer
          ? AspectRatio(
              aspectRatio: controller.player!.value.aspectRatio,
              child: VideoPlayer(controller.player!),
            )
          : AssetGenImage(item.cover).image(
              fit: BoxFit.fill,
              height: double.infinity,
            ),
    );
  }
}

class _JzxOptions extends GetView<JzxVideoController> {
  const _JzxOptions(this.item, {super.key});

  final Rx<JzxMediaData> item;

  @override
  Widget build(BuildContext context) {
    return Obx(() => Positioned(
          right: 16,
          top: 150.w + kNavigationBarHeight,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Stack(
                children: [
                  JzxUserFrame(item.value.user.avatar, 70.w),
                  Positioned(
                    right: 5,
                    bottom: 0,
                    child: InkWell(
                      onTap: () {
                        controller.followOrCancel2(item);
                      },
                      child: item.value.isFollowed
                          ? Assets.images.icFollowed.image(width: 23.w)
                          : Assets.images.icFollow.image(width: 23.w),
                    ),
                  )
                ],
              ),
              // Stack(
              //   alignment: Alignment.center,
              //   children: [
              //     JzxNetworkAssets(item.user.avatar, width: 55.w, radius: 100),
              //     Assets.images.icFrame4.image(width: 70.w),
              //     Positioned(
              //       right: 5,
              //       bottom: 0,
              //       child: Assets.images.icFollow.image(width: 23.w),
              //     )
              //   ],
              // ),
              JzxGaps.h32,
              InkWell(
                onTap: () {
                  controller.likeOrCancel(item);
                },
                child: item.value.isLiked
                    ? Assets.images.icLike.image(width: 60.w)
                    : Assets.images.icUnlike.image(width: 60.w),
              ),
              JzxGaps.h7,
              Text(item.value.like.format, style: myAppColors.white.font_16),
              JzxGaps.h10,
              InkWell(
                  onTap: () => controller.sendComment(item.value),
                  child: Assets.images.icComment.image(width: 60.w)),
              JzxGaps.h7,
              Text(item.value.follow.toString(),
                  style: myAppColors.white.font_16),
            ],
          ),
        ));
  }
}

class _JzxTitle extends StatelessWidget {
  const _JzxTitle({
    super.key,
    required this.item,
  });

  final JzxMediaData item;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const _JzxComment(),
          JzxGaps.h26,
          Text(
            item.title,
            style: myAppColors.white.font_16,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
}

class _JzxComment extends GetView<JzxVideoController> {
  const _JzxComment();

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 120.w,
      width: 270.w,
      child: GetBuilder<JzxVideoController>(
        init: controller,
        id: 'comments',
        autoRemove: false,
        assignId: true,
        builder: (_) {
          return AnimatedOpacity(
            opacity: controller.isShowComment ? 1 : 0,
            duration: const Duration(milliseconds: 300),
            child: ListView.separated(
              reverse: true,
              physics: controller.isShowComment
                  ? const BouncingScrollPhysics()
                  : const NeverScrollableScrollPhysics(),
              itemCount: controller.commentList.length,
              controller: controller.commentScorller,
              padding: EdgeInsets.zero,
              itemBuilder: (context, index) {
                final item = controller.commentList[index];
                return Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(4),
                      constraints: BoxConstraints(
                        maxWidth: 270.w,
                        minWidth: 136.w,
                      ),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(44.w),
                        color: const Color(0x4D000000),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          JzxNetworkAssets(
                            item.avatar,
                            width: 36.w,
                            radius: 100,
                          ),
                          // ClipOval(
                          //   child: Assets.images.appLogo.image(width: 36.w),
                          // ),
                          JzxGaps.w10,
                          ConstrainedBox(
                            constraints: BoxConstraints(maxWidth: 180.w),
                            child: Text(
                              item.content,
                              style: myAppColors.white.font_14,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ).paddingOnly(top: 5, right: 15),
                        ],
                      ),
                    ),
                  ],
                );
              },
              separatorBuilder: (context, index) => JzxGaps.h20,
            ),
          );
        },
      ),
    );
  }
}

class _JzxProgress extends GetView<JzxVideoController> {
  const _JzxProgress(this.showPlayer);

  final bool showPlayer;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Visibility(
        visible: !showPlayer,
        child: Center(
          child: LoopAnimationBuilder(
            tween: Tween(begin: 0.0, end: 1.0), // 100.0 to 200.0
            duration: const Duration(milliseconds: 700),
            builder: (context, value, child) {
              return Container(
                height: 3,
                width: Get.width * value,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
